package com.zut.Service.HttpNotWaitImpl;
import cn.hutool.core.codec.Base64;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zut.Pojo.JudgeResult;
import com.zut.Pojo.submissionsBody;
import com.zut.Service.HttpNotWait;
import com.zut.Util.HttpClientUtils;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class HttpNotWaitImpl  implements HttpNotWait{

    @Override
    public JudgeResult GoJudge(submissionsBody body) {

        try {
            String json = HttpClientUtils.post(BASEURL, JSONUtil.toJsonStr(body));
            System.err.println(json);
            return JSONToBean(json);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }


    }

    /**
     * 将字符串序列化为实例对象
     */
    private JudgeResult JSONToBean(String Json) {


        // 增加类型安全和空指针检查
        try {
            // 将Json字符串转换为Map对象
            JudgeResult judge = JSONUtil.toBean(Json, JudgeResult.class);
//            Map<String, Object> map = JSONUtil.toBean(Json, Map.class);
//            // 判断Map中是否包含键"submissions"且对应的值是List类型
//            if (map.containsKey("submissions") && map.get("submissions") instanceof List) {
//                // 将Map中键"submissions"对应的值转换为JudgeResult类型的List
//                List<JSONObject> list = (List<JSONObject>) map.get("submissions");
//
//                return list.parallelStream()
//                        .map(judge -> JSONUtil.toBean(judge, JudgeResult.class))
//                        .map(judge -> {
                            // 对judge对象的stdout属性进行Base64解码
                            judge.setStdout(Base64.decodeStr(judge.getStdout()));
                            judge.setStderr(Base64.decodeStr(judge.getStderr()));
                            // 对judge对象的compile_output属性进行Base64解码
                            judge.setCompile_output(Base64.decodeStr(judge.getCompile_output()));
                            // 对judge对象的message属性进行Base64解码
                            judge.setMessage(Base64.decodeStr(judge.getMessage()));
                            // 返回处理后的judge对象
//                            return judge;
//                        }).collect(Collectors.toList());  // 返回处理后的List
//            } else {
//                return Collections.emptyList(); // 返回空列表以避免空指针异常
//            }
            return    judge;
        } catch (Exception e) {
            e.printStackTrace();
            // 异常处理逻辑

        }
        return null;

    }

}
